<?php

namespace app\service;

use app\model\CartProducts;
use app\model\Products;
use app\model\ProductSkus;
use app\model\ProductDescriptions;
use app\model\Sellers;
class CartService
{

    protected $userId;
    protected $cartModel;
    public function __construct($userId)
    {
        $this->userId = $userId;
        $this->cartModel = new CartProducts();
    }
    
   public function getCartList(){
     // 查询购物车产品并关联产品信息、SKU信息、产品描述
        $cartItems = CartProducts::alias('cp')
            ->leftJoin('products p', 'cp.product_id = p.id')
            ->leftJoin('product_skus ps', 'cp.product_sku = ps.id')
            ->leftJoin('product_descriptions pd', 'p.id = pd.product_id')
            ->where('cp.customer_id', $this->userId)
            ->where('p.active', 1) // 只查询启用的产品
            ->where('pd.locale', 'zh_cn') // 中文描述
            ->field([
                'cp.id as cart_id',
                'cp.product_id',
                'cp.product_sku',
                'cp.quantity',
                'cp.selected',
                'p.images as product_images',
                'p.price as product_price',
                'p.variables as product_variables',
                'p.seller_id',
                'pd.name as product_name',
                'ps.price as sku_price',
                'ps.origin_price as sku_origin_price',
                'ps.variants as sku_variants',
                'ps.images as sku_images'
            ])
            ->select()
            ->toArray();
            
        if (empty($cartItems)) {
            return [
                'items' => [],
                'total_amount' => 0,
                'total_quantity' => 0
            ];
        }
        
        $totalAmount = 0;
        $totalQuantity = 0;
        $formattedItems = [];
        
        foreach ($cartItems as $item) {
            // 处理产品图片
            $productImages = json_decode($item['product_images'], true) ?: [];
            $skuImages = empty($item['sku_images'])?[]:json_decode($item['sku_images'], true);
            $images = !empty($skuImages) ? $skuImages : $productImages;
            $mainImage = !empty($images) ? $images[0] : '';
            $mainImage =(env('IMAGE_URL').$mainImage);
            // 处理SKU规格
            // 数据["0"]
            $skuVariants = empty($item['sku_variants'])?[]:json_decode($item['sku_variants'], true);
            // 数据[{"name": {"en": "color", "zh_cn": "颜色"}, "values": [{"name": {"en": "colro", "zh_cn": "蓝色"}, "image": ""}], "isImage": false}]
            $productVariants = empty($item['product_variables'])?[]:json_decode($item['product_variables'], true);
            $variantText = '';
            $variantDetails = [];
            
            // 根据SKU variants索引获取对应的产品规格信息
            if (!empty($skuVariants) && !empty($productVariants)) {
               list($variantText,$variantDetails) = getSkuVariant($skuVariants,$productVariants);
            }
            // 使用SKU价格，如果没有则使用产品价格
            $price = $item['sku_price'] > 0 ? $item['sku_price'] : $item['product_price'];
            $originPrice = $item['sku_origin_price'] > 0 ? $item['sku_origin_price'] : $price;
            // 计算小计
            $subtotal = $price * $item['quantity'];
            $totalAmount += $subtotal;
            $totalQuantity += $item['quantity'];
            $formattedItems[] = [
                'cart_id' => $item['cart_id'],
                'product_id' => $item['product_id'],
                'product_sku_id' => $item['product_sku'],
                'product_name' => $item['product_name'] ?: '未知商品',
                'product_image' => $mainImage,
                'sku_name' => $variantText,
                'sku_list' => $variantDetails,
                'price' => round($price, 2),
                'origin_price' => round($originPrice, 2),
                'quantity' => $item['quantity'],
                'subtotal' => round($subtotal, 2),
                'selected'=>false,//$item['selected']==1?true:false,
                'seller_id'=>(int)$item['seller_id'],
            ];
        }
        //重置购物车未选择
        $this->cartModel->where([
            'customer_id'=>$this->userId
        ])->update(['selected'=>0]);
        // 按照供应商分组
        $sellerIds = array_unique(array_column($formattedItems, 'seller_id'));
        $sellerNames = Sellers::whereIn('id',$sellerIds)->field('store_name','id')->select()->toArray();
        $sellerNames =empty($sellerNames)?[]: array_column( $sellerNames,'name','id');
        $groupedItems = [];
        foreach ($formattedItems as $item) {
            $item['seller_name'] = $sellerNames[$item['seller_id']]??'平台自营';
            $groupedItems[$item['seller_id']][
                'seller_name'
            ] = $item['seller_name'];
            $groupedItems[$item['seller_id']]['products'][] = $item;
        }
        return [
            'items' => $groupedItems,
            'total_amount' => round($totalAmount, 2),
            'total_quantity' => $totalQuantity
        ];
   }


    // 自增购物车数量
    public function increment($data)
    {
        if (empty($data['cart_id'])) {
            throw new \Exception('参数错误');
        }
        $cartId = (int)$data['cart_id'];
        $quantity = (int)$data['quantity']??1;
        $cartItem = $this->cartModel->where([
            'id'=>$cartId,
            'customer_id'=>$this->userId
        ])->find();
        if (!$cartItem) {
            throw new \Exception('购物车项不存在');
        }
        $cartItem->quantity += $quantity;
        $cartItem->save();
        return [];
    }

    // 自减购物车数量
    public function decrement($data)
    {
        if (empty($data['cart_id'])) {
            throw new \Exception('参数错误');
        }
        $cartId = (int)$data['cart_id'];
        $quantity = (int)$data['quantity']??1;
        $cartItem = $this->cartModel->where([
            'id'=>$cartId,
            'customer_id'=>$this->userId
        ])->find();
        if (!$cartItem) {
            throw new \Exception('购物车项不存在');
        }
        $cartItem->quantity -= $quantity;
        $cartItem->save();
        return [];
    }

    // 删除购物车产品
    public function deleteCartItem($cartId)
    {
        if (empty($cartId)) {
            throw new \Exception('参数错误');
        }
        $cartItem = $this->cartModel->whereIn('id',explode(',',$cartId))->where([
            'customer_id'=>$this->userId
        ])->find();
        if (!$cartItem) {
            throw new \Exception('购物车项不存在');
        }
        $cartItem->delete();
        return [];
    }

    // 清空用户购物车
    public function clearCart()
    {
        $this->cartModel->where(['customer_id'=>$this->userId])->delete();
        return [];
    }


    // 购物车选中
    public function selectedCartItem($cartIds)
    {
        if (empty($cartIds)) {
            throw new \Exception('参数错误');
        }
        $this->cartModel->whereIn('id',explode(',',$cartIds))->where([
            'customer_id'=>$this->userId
        ])->update(['selected'=>1]);
        return [];
    }
}